package com.dingreading.cloud.app.controller;

import com.aliyuncs.facebody.model.v20191230.*;
import com.dingreading.cloud.app.entity.Corporations;
import com.dingreading.cloud.app.entity.Members;
import com.dingreading.cloud.app.entity.StoreSignIn;
import com.dingreading.cloud.app.entity.Stores;
import com.dingreading.cloud.app.service.CorporationsService;
import com.dingreading.cloud.app.service.MembersService;
import com.dingreading.cloud.app.service.StoreSignInService;
import com.dingreading.cloud.app.util.FaceDetectUtil;
import com.dingreading.cloud.app.util.StoreSignInUtil;
import com.dingreading.cloud.app.util.UidUtil;
import com.dingreading.cloud.app.util.WxTemplateUtil;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.EnumType;
import com.dingreading.cloud.common.util.NepUtil;
import com.dingreading.cloud.common.util.WxGzhUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/app/face")
@Api(tags = "APP-人脸搜索相关")
public class AppFaceController {

    @Resource
    private CorporationsService corporationsService;
    @Resource
    private MembersService membersService;
    @Resource
    private StoreSignInService storeSignInService;

    @ApiOperation(value = "app添加人脸数据")
    @PostMapping(value = "/addFaceEntity", produces = "application/json; charset=UTF-8")
    public R<Object> addFaceEntity(
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid,
            @ApiParam(value = "正常人脸图片") @RequestParam(value = "faceImg") String faceImg
    ) throws Exception {
//        Object member = UidUtil.getMember(memberUid);
//        if (member instanceof String) return R.fail(member.toString());
//        Members members = (Members) member;
//
//        if (members.getFaceUpStatus() != null && members.getFaceUpStatus() == 1) {
//            return R.fail(4015, "已上传过,操作失败");
//        }
//        // 查询该会员id是否存在人脸样本
//        GetFaceEntityResponse getFaceEntityResponse = FaceDetectUtil.getFaceEntityByEntityId(String.valueOf(members.getId()));
//        if (StringUtils.isBlank(getFaceEntityResponse.getData().getEntityId())) {
//            // 新增人脸样本
//            AddFaceEntityResponse faceEntityResponse = FaceDetectUtil.addFaceEntity(String.valueOf(members.getId()));
//            String requestIdOne = faceEntityResponse.getRequestId();
//        }
//        // 新增人脸数据
//        AddFaceResponse faceResponse = FaceDetectUtil.addFace(String.valueOf(members.getId()), faceImg);
//        if (faceResponse.getData() == null) {
//            return R.fail(4016, "添加人脸异常,操作失败");
//        }
//        String faceId = faceResponse.getData().getFaceId();
//        members.setFaceId(faceId);
//        members.setFaceUpStatus(1);
//        members.setFaceImg(faceImg);
//        membersService.saveOrUpdate(members);
//        return R.ok();
        return R.fail("功能已暂停，请升级App版本");
    }

    @ApiOperation(value = "app删除人脸样本")
    @PostMapping(value = "/deleteFaceEntity", produces = "application/json; charset=UTF-8")
    public R<Object> deleteFaceEntity(@ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid) throws Exception {
//        Object member = UidUtil.getMember(memberUid);
//        if (member instanceof String) return R.fail(member.toString());
//        Members members = (Members) member;
//        // 删除人脸样本
//        DeleteFaceEntityResponse response = FaceDetectUtil.deleteFaceEntity(String.valueOf(members.getId()));
//
//        members.setFaceId("");
//        members.setFaceUpStatus(-1);
//        members.setFaceImg("");
//        membersService.saveOrUpdate(members);
//        return R.ok();
        return R.fail("功能已暂停，请升级App版本");
    }

    @ApiOperation(value = "app人脸签到")
    @PostMapping(value = "/toStoreFace", produces = "application/json; charset=UTF-8")
    public R<Object> toStoreFace(
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "人脸图片") @RequestParam(value = "faceImg") String faceImg
    ) throws Exception {
//        Object store = UidUtil.getStore(storeUid);
//        if (store instanceof String) return R.fail(store.toString());
//        Stores stores = (Stores) store;
//        String corpUid = stores.getCorpUid();
//        Long storeId = stores.getId();
//        String storeName = stores.getStoreName();
//        // 人脸搜索
//        SearchFaceResponse response = FaceDetectUtil.searchFaceEntity(faceImg);
////        System.out.println("response = \n" + JSONObject.toJSONString(response));
//        List<SearchFaceResponse.Data.MatchListItem> matchList = response.getData().getMatchList();
//        if (matchList == null || matchList.size() <= 0) {
//            return R.fail(4016, "未搜索到,操作失败");
//        }
//        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> realFaceList = new ArrayList<>();
//
//        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> faceList = matchList.get(0).getFaceItems();
//        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : faceList) {
//            if (face.getConfidence() >= 75f) {
//                realFaceList.add(face);
//            }
//        }
//        if (CollectionUtils.isEmpty(realFaceList)) {
//            return R.fail(4016, "未搜索到,操作失败");
//        }
//        Members members = null;
//        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : realFaceList) {
//            Members member = membersService.getById(Long.valueOf(face.getEntityId()));
//            if (member != null && storeId.equals(member.getStoreId())) {
//                members = member;
//                break;
//            }
//        }
//        if (members == null) {
//            return R.fail(4016, "没有查到会员,操作失败");
//        }
//
//        String timeYmd = DateUtil.getNowDateStr();
//        List<StoreSignIn> noLeaveTimeTags = storeSignInService.getByMemberIdAndStatusAndTimeYmd(members.getId(), 1, timeYmd);
//        if (CollectionUtils.isNotEmpty(noLeaveTimeTags)) {
//            return R.fail(4016, members.getFullName() + "已签到,不能重复签到");
//        }
//        Date time = DateUtil.getNowDatetime();
//        members.setStoreStatus(1);
//        members.setStoreStatusTime(time);
//        // 修改在店状态，读书天数
//        Integer readDays = NepUtil.nullToZero(members.getReadDays());
//        List<StoreSignIn> haveTimeTags = storeSignInService.getByMemberIdAndStatusAndTimeYmd(members.getId(), null, timeYmd);
//        if (CollectionUtils.isEmpty(haveTimeTags)) {
//            members.setReadDays(readDays + 1);
//        }
//        membersService.saveOrUpdate(members);
//        // 生成签到记录
//        StoreSignIn storeSignIn = StoreSignInUtil.getStoreSignIn(members, corpUid, storeId, storeUid, storeName, time, time, null, null);
//        storeSignInService.saveOrUpdate(storeSignIn);
//
//        String tokenData = WxGzhUtil.getWxAccessToken();
//        if (StringUtils.isNotBlank(tokenData)) {
//            WxTemplateUtil.wxSendToRelatives(members, 0L, NepUtil.nullToZero(storeName), EnumType.SignInType.SIGN_IN.getType(), tokenData);
//        } else {
//            System.out.println("人脸签到 = " + "微信accessToken获取失败");
//        }
//
//        return R.ok(members.getFullName());
        return R.fail("功能已暂停，请升级App版本");
    }

    @ApiOperation(value = "app人脸签退")
    @PostMapping(value = "/leaveStoreFace", produces = "application/json; charset=UTF-8")
    public R<Object> leaveStoreFace(
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "人脸图片") @RequestParam(value = "faceImg") String faceImg
    ) throws Exception {
//        Object store = UidUtil.getStore(storeUid);
//        if (store instanceof String) return R.fail(store.toString());
//        Stores stores = (Stores) store;
//        if (StringUtils.isBlank(faceImg)) {
//            return R.fail(4016, "信息异常,操作失败");
//        }
//        // 人脸搜索
//        SearchFaceResponse response = FaceDetectUtil.searchFaceEntity(faceImg);
//        List<SearchFaceResponse.Data.MatchListItem> matchList = response.getData().getMatchList();
//        if (matchList == null || matchList.size() <= 0) {
//            return R.fail(4016, "未搜索到,操作失败");
//        }
//        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> faceList = matchList.get(0).getFaceItems();
//        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> realFaceList = new ArrayList<>();
//        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : faceList) {
//            if (face.getConfidence() >= 75f) {
//                realFaceList.add(face);
//            }
//        }
//        if (CollectionUtils.isEmpty(realFaceList)) {
//            return R.fail(4016, "未搜索到,操作失败");
//        }
//        Members members = null;
//        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : realFaceList) {
//            Members member = membersService.getById(Long.valueOf(face.getEntityId()));
//            if (member != null && stores.getId().equals(member.getStoreId())) {
//                members = member;
//                break;
//            }
//        }
//        if (members == null) {
//            return R.fail(4016, "没有查到会员,操作失败");
//        }
//        String timeYmd = DateUtil.getNowDateStr();
//        Date nowDate = DateUtil.getNowDatetime();
//        List<StoreSignIn> signInList = storeSignInService.getByMemberIdAndStatusAndTimeYmd(members.getId(), 1, timeYmd);
//        if (CollectionUtils.isEmpty(signInList)) {
//            return R.fail(4016, "请先去签到");
//        }
//        for (StoreSignIn storeSignIn : signInList) {
//            storeSignIn.setStatus(2);
//            storeSignIn.setLeaveTime(nowDate);
//            storeSignIn.setDuration((nowDate.getTime() - storeSignIn.getArrivalTime().getTime()) / 1000L);
//        }
//        storeSignInService.saveOrUpdateBatch(signInList);
//
//        members.setStoreStatus(2);
//        members.setStoreStatusTime(nowDate);
//        membersService.saveOrUpdate(members);
//
//        // 签退微信消息
//        String tokenData = WxGzhUtil.getWxAccessToken();
//        if (StringUtils.isNotBlank(tokenData)) {
//            WxTemplateUtil.wxSendToRelatives(members, signInList.get(0).getDuration(), NepUtil.nullToZero(stores.getStoreName()), EnumType.SignInType.SIGN_OUT.getType(), tokenData);
//        } else {
//            System.out.println("人脸签退 = " + "微信accessToken获取失败");
//        }
//        return R.ok(members.getFullName());
        return R.fail("功能已暂停，请升级App版本");
    }

    @ApiOperation(value = "app通过人脸图片查找用户")
    @PostMapping(value = "/getMemberByFaceImg", produces = "application/json; charset=UTF-8")
    public R<Object> getMemberByFaceImg(
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "人脸图片") @RequestParam(value = "faceImg") String faceImg
    ) throws Exception {
//        Object store = UidUtil.getStore(storeUid);
//        if (store instanceof String) return R.fail(store.toString());
//        Stores stores = (Stores) store;
//        if (StringUtils.isBlank(faceImg)) {
//            return R.fail(4016, "信息异常,操作失败");
//        }
//        String corpUid = stores.getCorpUid();
//        Long storeId = stores.getId();
//        String storeName = stores.getStoreName();
//        // 人脸搜索
//        SearchFaceResponse response = FaceDetectUtil.searchFaceEntity(faceImg);
//        List<SearchFaceResponse.Data.MatchListItem> matchList = response.getData().getMatchList();
//        if (matchList == null || matchList.size() <= 0) {
//            return R.fail(4016, "未搜索到,操作失败");
//        }
//        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> faceList = matchList.get(0).getFaceItems();
//        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> realFaceList = new ArrayList<>();
//        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : faceList) {
//            if (face.getConfidence() >= 75f) {
//                realFaceList.add(face);
//            }
//        }
//        if (CollectionUtils.isEmpty(realFaceList)) {
//            return R.fail(4016, "未搜索到,操作失败");
//        }
//        Members members = null;
//        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : realFaceList) {
//            Members member = membersService.getById(Long.valueOf(face.getEntityId()));
//            if (member != null && storeId.equals(member.getStoreId())) {
//                members = member;
//                break;
//            }
//        }
//        if (members == null) {
//            return R.fail(4016, "没有查到会员,操作失败");
//        }
//        String timeYmd = DateUtil.getNowDateStr();
//        List<StoreSignIn> todaySignInList = storeSignInService.getByMemberIdAndStatusAndTimeYmd(members.getId(), 1, timeYmd);
//        //当天未签到，则补签到
//        if (CollectionUtils.isEmpty(todaySignInList)) {
//            Date time = DateUtil.getNowDatetime();
//            // 修改在店状态，读书天数
//            members.setStoreStatus(1);
//            members.setStoreStatusTime(time);
//            // 修改在店状态，读书天数
//            Integer readDays = NepUtil.nullToZero(members.getReadDays());
//            List<StoreSignIn> haveTimeTags = storeSignInService.getByMemberIdAndStatusAndTimeYmd(members.getId(), null, timeYmd);
//            if (CollectionUtils.isEmpty(haveTimeTags)) {
//                members.setReadDays(readDays + 1);
//            }
//            membersService.saveOrUpdate(members);
//            // 生成签到记录
//            StoreSignIn storeSignIn = StoreSignInUtil.getStoreSignIn(members, corpUid, storeId, storeUid, storeName, time, time, null, null);
//            storeSignInService.saveOrUpdate(storeSignIn);
//            // 处理微信消息提醒
//            String tokenData = WxGzhUtil.getWxAccessToken();
//            if (StringUtils.isNotBlank(tokenData)) {
//                WxTemplateUtil.wxSendToRelatives(members, 0L, NepUtil.nullToZero(storeName), EnumType.SignInType.SIGN_IN.getType(), tokenData);
//            } else {
//                System.out.println("通过人脸图片查找用户 = " + "微信accessToken获取失败");
//            }
//        }
//        result = R.ok(members);
//        return result;
        return R.fail("功能已暂停，请升级App版本");
    }

    @ApiOperation(value = "app添加人脸数据v2")
    @PostMapping(value = "/v2/addFaceEntity", produces = "application/json; charset=UTF-8")
    public R<Object> addFaceEntity(
            @ApiParam(value = "手机系统 1.安卓 2.ios") @RequestParam(value = "os") Integer os,
            @ApiParam(value = "设备标识") @RequestParam(value = "deviceId") String deviceId,
            @ApiParam(value = "版本号") @RequestParam(value = "versionCode") Integer versionCode,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid,
            @ApiParam(value = "正常人脸图片") @RequestParam(value = "faceImg") String faceImg
    ) throws Exception {
        Object store = UidUtil.getStore(storeUid);
        if (store instanceof String)
            return R.fail(store.toString());

        Object member = UidUtil.getMember(memberUid);
        if (member instanceof String)
            return R.fail(member.toString());
        Members members = (Members) member;

        Corporations corporations = corporationsService.getByUid(members.getCorpUid());
        String judgeCorp = UidUtil.judgeCorp(corporations);
        if (StringUtils.isNotBlank(judgeCorp))
            return R.fail(judgeCorp);

        if (members.getFaceUpStatus() != null && members.getFaceUpStatus() == 1) {
            return R.fail(4015, "已上传过,操作失败");
        }
        // 查询该会员id是否存在人脸样本
        GetFaceEntityResponse getFaceEntityResponse = FaceDetectUtil.getFaceEntityByEntityId(String.valueOf(members.getId()));
        if (StringUtils.isBlank(getFaceEntityResponse.getData().getEntityId())) {
            // 新增人脸样本
            AddFaceEntityResponse faceEntityResponse = FaceDetectUtil.addFaceEntity(String.valueOf(members.getId()));
            String requestIdOne = faceEntityResponse.getRequestId();
        }
        // 新增人脸数据
        AddFaceResponse faceResponse = FaceDetectUtil.addFace(String.valueOf(members.getId()), faceImg);
        if (faceResponse.getData() == null) {
            return R.fail(4016, "添加人脸异常,操作失败");
        }
        String faceId = faceResponse.getData().getFaceId();

        // 保存会员的人脸信息
        membersService.saveFaceInfo(memberUid, faceImg, faceId);
        return R.ok();
    }

    @ApiOperation(value = "app删除人脸样本v2")
    @PostMapping(value = "/v2/deleteFaceEntity", produces = "application/json; charset=UTF-8")
    public R<Object> deleteFaceEntity(
            @ApiParam(value = "手机系统 1.安卓 2.ios") @RequestParam(value = "os") Integer os,
            @ApiParam(value = "设备标识") @RequestParam(value = "deviceId") String deviceId,
            @ApiParam(value = "版本号") @RequestParam(value = "versionCode") Integer versionCode,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "会员uid") @RequestParam(value = "memberUid") String memberUid
    ) throws Exception {
        Object store = UidUtil.getStore(storeUid);
        if (store instanceof String)
            return R.fail(store.toString());

        Object member = UidUtil.getMember(memberUid);
        if (member instanceof String)
            return R.fail(member.toString());
        Members members = (Members) member;

        Corporations corporations = corporationsService.getByUid(members.getCorpUid());
        String judgeCorp = UidUtil.judgeCorp(corporations);
        if (StringUtils.isNotBlank(judgeCorp))
            return R.fail(judgeCorp);

        // 删除人脸样本
        DeleteFaceEntityResponse response = FaceDetectUtil.deleteFaceEntity(String.valueOf(members.getId()));

        // 删除会员的人脸信息
        membersService.deleteFaceInfo(memberUid);
        return R.ok();
    }

    @ApiOperation(value = "app人脸签到v2")
    @PostMapping(value = "/v2/toStoreFace", produces = "application/json; charset=UTF-8")
    public R<Object> toStoreFace(
            @ApiParam(value = "手机系统 1.安卓 2.ios") @RequestParam(value = "os") Integer os,
            @ApiParam(value = "设备标识") @RequestParam(value = "deviceId") String deviceId,
            @ApiParam(value = "版本号") @RequestParam(value = "versionCode") Integer versionCode,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "人脸图片") @RequestParam(value = "faceImg") String faceImg
    ) throws Exception {
        Object store = UidUtil.getStore(storeUid);
        if (store instanceof String)
            return R.fail(store.toString());
        Stores stores = (Stores) store;

        Corporations corporations = corporationsService.getByUid(stores.getCorpUid());
        String judgeCorp = UidUtil.judgeCorp(corporations);
        if (StringUtils.isNotBlank(judgeCorp))
            return R.fail(judgeCorp);

        if (StringUtils.isBlank(faceImg))
            return R.fail(4016, "未上传人脸图片");

        String corpUid = stores.getCorpUid();
        Long storeId = stores.getId();
        String storeName = stores.getStoreName();
        // 人脸搜索
        SearchFaceResponse response = FaceDetectUtil.searchFaceEntity(faceImg);
//        System.out.println("response = \n" + JSONObject.toJSONString(response));
        List<SearchFaceResponse.Data.MatchListItem> matchList = response.getData().getMatchList();
        if (matchList == null || matchList.size() <= 0)
            return R.fail(4016, "未搜索到,操作失败");

        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> realFaceList = new ArrayList<>();

        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> faceList = matchList.get(0).getFaceItems();
        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : faceList) {
            if (face.getConfidence() >= 75f) {
                realFaceList.add(face);
            }
        }
        if (CollectionUtils.isEmpty(realFaceList))
            return R.fail(4016, "未搜索到,操作失败");

        Members members = null;
        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : realFaceList) {
            Members member = membersService.getById(Long.valueOf(face.getEntityId()));
            if (member != null && storeId.equals(member.getStoreId())) {
                members = member;
                break;
            }
        }
        if (members == null)
            return R.fail(4016, "没有查到会员,操作失败");

        String timeYmd = DateUtil.getNowDateStr();
        List<StoreSignIn> noLeaveTimeTags = storeSignInService.getByMemberIdAndStatusAndTimeYmd(members.getId(), 1, timeYmd);
        if (CollectionUtils.isNotEmpty(noLeaveTimeTags))
            return R.fail(4016, members.getFullName() + "已签到,不能重复签到");

        Date time = DateUtil.getNowDatetime();
        // 修改在店状态，读书天数
        int readDays = NepUtil.nullToZero(members.getReadDays());
        List<StoreSignIn> haveTimeTags = storeSignInService.getByMemberIdAndStatusAndTimeYmd(members.getId(), null, timeYmd);
        if (CollectionUtils.isEmpty(haveTimeTags))
            readDays += 1;
        membersService.updateStoreStatus(members.getUid(), 1, readDays, time);

        // 生成签到记录
        StoreSignIn storeSignIn = StoreSignInUtil.getStoreSignIn(members, corpUid, storeId, storeUid, storeName, time, null, null);
        storeSignInService.saveOrUpdate(storeSignIn);

        String tokenData = WxGzhUtil.getWxAccessToken();
        if (StringUtils.isNotBlank(tokenData)) {
            WxTemplateUtil.wxSendToRelatives(members, 0L, NepUtil.nullToZero(storeName), EnumType.SignInType.SIGN_IN.getType(), tokenData);
        } else {
            System.out.println("人脸签到 = " + "微信accessToken获取失败");
        }

        return R.ok(members.getFullName());
    }

    @ApiOperation(value = "app人脸签退v2")
    @PostMapping(value = "/v2/leaveStoreFace", produces = "application/json; charset=UTF-8")
    public R<Object> leaveStoreFace(
            @ApiParam(value = "手机系统 1.安卓 2.ios") @RequestParam(value = "os") Integer os,
            @ApiParam(value = "设备标识") @RequestParam(value = "deviceId") String deviceId,
            @ApiParam(value = "版本号") @RequestParam(value = "versionCode") Integer versionCode,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "人脸图片") @RequestParam(value = "faceImg") String faceImg
    ) throws Exception {
        Object store = UidUtil.getStore(storeUid);
        if (store instanceof String)
            return R.fail(store.toString());
        Stores stores = (Stores) store;

        Corporations corporations = corporationsService.getByUid(stores.getCorpUid());
        String judgeCorp = UidUtil.judgeCorp(corporations);
        if (StringUtils.isNotBlank(judgeCorp))
            return R.fail(judgeCorp);

        if (StringUtils.isBlank(faceImg))
            return R.fail(4016, "未上传人脸图片");

        // 人脸搜索
        SearchFaceResponse response = FaceDetectUtil.searchFaceEntity(faceImg);
        List<SearchFaceResponse.Data.MatchListItem> matchList = response.getData().getMatchList();
        if (matchList == null || matchList.size() <= 0) {
            return R.fail(4016, "未搜索到,操作失败");
        }
        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> faceList = matchList.get(0).getFaceItems();
        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> realFaceList = new ArrayList<>();
        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : faceList) {
            if (face.getConfidence() >= 75f) {
                realFaceList.add(face);
            }
        }
        if (CollectionUtils.isEmpty(realFaceList))
            return R.fail(4016, "未搜索到,操作失败");

        Members members = null;
        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : realFaceList) {
            Members member = membersService.getById(Long.valueOf(face.getEntityId()));
            if (member != null && stores.getId().equals(member.getStoreId())) {
                members = member;
                break;
            }
        }
        if (members == null)
            return R.fail(4016, "没有查到会员,操作失败");

        String timeYmd = DateUtil.getNowDateStr();
        Date nowDate = DateUtil.getNowDatetime();
        List<StoreSignIn> signInList = storeSignInService.getByMemberIdAndStatusAndTimeYmd(members.getId(), 1, timeYmd);
        if (CollectionUtils.isEmpty(signInList))
            return R.fail(4016, "请先去签到");

        for (StoreSignIn storeSignIn : signInList) {
            storeSignIn.setStatus(2);
            storeSignIn.setLeaveTime(nowDate);
            storeSignIn.setDuration((nowDate.getTime() - storeSignIn.getArrivalTime().getTime()) / 1000L);
        }
        storeSignInService.saveOrUpdateBatch(signInList);

        // 更新会员的在店信息
        membersService.updateStoreStatus(members.getUid(), 2, null, nowDate);

        // 签退微信消息
        String tokenData = WxGzhUtil.getWxAccessToken();
        if (StringUtils.isNotBlank(tokenData)) {
            WxTemplateUtil.wxSendToRelatives(members, signInList.get(0).getDuration(), NepUtil.nullToZero(stores.getStoreName()), EnumType.SignInType.SIGN_OUT.getType(), tokenData);
        } else {
            System.out.println("人脸签退 = " + "微信accessToken获取失败");
        }
        return R.ok(members.getFullName());
    }

    @ApiOperation(value = "app通过人脸图片查找用户v2")
    @PostMapping(value = "/v2/getMemberByFaceImg", produces = "application/json; charset=UTF-8")
    public R<Object> getMemberByFaceImg(
            @ApiParam(value = "手机系统 1.安卓 2.ios") @RequestParam(value = "os") Integer os,
            @ApiParam(value = "设备标识") @RequestParam(value = "deviceId") String deviceId,
            @ApiParam(value = "版本号") @RequestParam(value = "versionCode") Integer versionCode,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "人脸图片") @RequestParam(value = "faceImg") String faceImg
    ) throws Exception {
        Object store = UidUtil.getStore(storeUid);
        if (store instanceof String)
            return R.fail(store.toString());
        Stores stores = (Stores) store;

        Corporations corporations = corporationsService.getByUid(stores.getCorpUid());
        String judgeCorp = UidUtil.judgeCorp(corporations);
        if (StringUtils.isNotBlank(judgeCorp))
            return R.fail(judgeCorp);

        if (StringUtils.isBlank(faceImg))
            return R.fail(4016, "未上传人脸图片");

        String corpUid = stores.getCorpUid();
        Long storeId = stores.getId();
        String storeName = stores.getStoreName();
        // 人脸搜索
        SearchFaceResponse response = FaceDetectUtil.searchFaceEntity(faceImg);
        List<SearchFaceResponse.Data.MatchListItem> matchList = response.getData().getMatchList();
        if (matchList == null || matchList.size() <= 0)
            return R.fail(4016, "未搜索到,操作失败");

        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> faceList = matchList.get(0).getFaceItems();
        List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> realFaceList = new ArrayList<>();
        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : faceList) {
            if (face.getConfidence() >= 75f) {
                realFaceList.add(face);
            }
        }
        if (CollectionUtils.isEmpty(realFaceList))
            return R.fail(4016, "未搜索到,操作失败");

        Members members = null;
        for (SearchFaceResponse.Data.MatchListItem.FaceItemsItem face : realFaceList) {
            Members member = membersService.getById(Long.valueOf(face.getEntityId()));
            if (member != null && storeId.equals(member.getStoreId())) {
                members = member;
                break;
            }
        }
        if (members == null)
            return R.fail(4016, "没有查到会员,操作失败");

        String timeYmd = DateUtil.getNowDateStr();
        List<StoreSignIn> todaySignInList = storeSignInService.getByMemberIdAndStatusAndTimeYmd(members.getId(), null, timeYmd);
        //当天未签到，则补签到
        if (CollectionUtils.isEmpty(todaySignInList)) {
            Date time = DateUtil.getNowDatetime();
            // 修改在店状态，读书天数
            int readyDay = NepUtil.nullToZero(members.getReadDays());
            membersService.updateStoreStatus(members.getUid(), 1, readyDay + 1, time);

            // 生成签到记录
            StoreSignIn storeSignIn = StoreSignInUtil.getStoreSignIn(members, corpUid, storeId, storeUid, storeName, time, null, null);
            storeSignInService.saveOrUpdate(storeSignIn);

            // 处理微信消息提醒
            String tokenData = WxGzhUtil.getWxAccessToken();
            if (StringUtils.isNotBlank(tokenData)) {
                WxTemplateUtil.wxSendToRelatives(members, 0L, NepUtil.nullToZero(storeName), EnumType.SignInType.SIGN_IN.getType(), tokenData);
            } else {
                System.out.println("通过人脸图片查找用户 = " + "微信accessToken获取失败");
            }
        }
        return R.ok(members);
    }

}
